package four;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author      : yang.xp
 * @date        : 2021/12/9 15:09
 * @description : reentrantLock1 和 reentrantLock2 产生死锁。然后thread2.interrupt()自己中断自己。真正运行完成的只有Thread1
 */
public class LockDemo6 implements Runnable {

    public static ReentrantLock reentrantLock1 = new ReentrantLock();
    public static ReentrantLock reentrantLock2 = new ReentrantLock();

    int lock;

    public LockDemo6(int lock) {
        this.lock = lock;
    }

    @Override
    public void run() {
        try {
            if (lock == 1) {
                reentrantLock1.lockInterruptibly();
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                reentrantLock2.lockInterruptibly();
            } else {
                reentrantLock2.lockInterruptibly();
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                reentrantLock1.lockInterruptibly();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (reentrantLock1.isHeldByCurrentThread()) {
                reentrantLock1.unlock();
            }
            if (reentrantLock2.isHeldByCurrentThread()) {
                reentrantLock2.unlock();
            }
            System.out.println(Thread.currentThread().getId() + ":线程退出");
        }
    }

    public static void main(String[] args) throws InterruptedException {
        LockDemo6 lockDemo1 = new LockDemo6(1);
        LockDemo6 lockDemo2 = new LockDemo6(2);
        Thread thread1 = new Thread(lockDemo1);
        Thread thread2 = new Thread(lockDemo2);
        thread1.start();
        thread2.start();
        Thread.sleep(1000);
//        thread2.interrupt();
    }
}
